package com.ilove.model;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;


public class DataAccess {

	public static String getData(String serverUrl) throws IOException {
		HttpConnection connection = null;
		InputStream inputstream = null;
		String str = null;
		int actual = 0;
		try {
			connection = (HttpConnection) Connector.open(serverUrl);
			connection.setRequestMethod(HttpConnection.GET);
			connection.setRequestProperty("Connection", "close");
			if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
				inputstream = connection.openInputStream();
				int length = (int) connection.getLength();
				if (length != -1) {
					byte[] incomingData = new byte[length];
					actual = inputstream.read(incomingData);
					str = new String(incomingData, 0, actual, "UTF-8");
				} else {
					ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
					int ch;
					while ((ch = inputstream.read()) != -1) {
						bytestream.write(ch);
					}
					str = new String(bytestream.toByteArray(), 0, bytestream
							.size(), "UTF-8");
					bytestream.close();
				}
			}
		} catch (IOException error) {
		} finally {
			if (inputstream != null) {
				try {
					inputstream.close();
				} catch (Exception error) {
					/* log error */
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception error) {
					/* log error */
				}
			}
		}
		return str;
	}
	/*--------------------------------------------------
	 * Open connection and download png into a byte array.
	 *-------------------------------------------------*/
	public static Image getImage(String url) throws IOException {
		System.out.println(url);
		HttpConnection connection = (HttpConnection) Connector.open(url,
				Connector.READ);
		connection.setRequestMethod(HttpConnection.GET);
		DataInputStream iStrm = connection.openDataInputStream();
		ByteArrayOutputStream bStrm = null;
		Image im = null;

		try {
			// ContentConnection includes a length method
			byte imageData[];
			int length = (int) connection.getLength();
			if (length != -1) {
				imageData = new byte[length];
				// Read the png into an array
				iStrm.readFully(imageData);
			} else // Length not available...
			{
				bStrm = new ByteArrayOutputStream();
				int ch;
				while ((ch = iStrm.read()) != -1)
					bStrm.write(ch);
				imageData = bStrm.toByteArray();
				bStrm.close();
			}
			// Create the image from the byte array
			im = Image.createImage(imageData, 0, imageData.length);
		} finally {
			// Clean up
			if (iStrm != null)
				iStrm.close();
			if (connection != null)
				connection.close();
			if (bStrm != null)
				bStrm.close();
		}
		return (im == null ? null : im);
	}

	public static String[] split(String original, String separator) {
		Vector nodes = new Vector();
		// Parse nodes into vector
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		// Get the last node
		nodes.addElement(original);
		// Create split string array
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++) {
				result[loop] = (String) nodes.elementAt(loop);
			}
		}
		return result;
	}

	public static String replaceOld(final String aInput,
			final String aOldPattern, final String aNewPattern) {
		if (aOldPattern.equals("")) {
			throw new IllegalArgumentException("Old pattern must have content.");
		}

		final StringBuffer result = new StringBuffer();
		int startIdx = 0;
		int idxOld = 0;
		while ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= 0) {
			result.append(aInput.substring(startIdx, idxOld));
			result.append(aNewPattern);
			startIdx = idxOld + aOldPattern.length();
		}
		result.append(aInput.substring(startIdx));
		return result.toString();
	}

	public static String proccessData(String[] arrString, int length) {
		String arr = "";
		int count = 0;
		for (int i = 0; i < arrString.length; i++) {
			arrString[i] = replaceOld(arrString[i], "<br>", "");
			count += arrString[i].length();
			if (count < length) {
				arr = arr + " ";
			} else {
				arr = arr + "@@@";
				count = 0;
			}
			arr = arr + arrString[i];
		}
		return arr;
	}

}
